package com.gensdai.leliang.Encrypt;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

/**
 * 加密方式s
 */
public class DesEncrypt {
	private static byte[] iv = { 1, 2, 3, 4, 5, 6, 7, 8 };
	public static final String DES_PUBLIC_ENCRYPT_KEY = "6Ta4OaHZdpA="; // DES公钥key
	public static final String DES_PRIVATE_ENCRYPT_KEY = "6Tg2OaZhdpB";

	private static byte[] desKey;
	private static String key = "6Ta4OaHZdpA=";

	public static String encrypt(String message, String encryptKey) {
		Cipher cipher;
		byte[] encryptedData = null;
		try {
			cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

			// SecretKeySpec secretKey = new
			// SecretKeySpec(FixSize(encryptKey.getBytes()), "DES");

			DESKeySpec desKeySpec = new DESKeySpec(encryptKey.getBytes("UTF-8"));
			SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
			SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
			// IvParameterSpec zeroIv = new IvParameterSpec(
			// FixSize(key.getBytes("UTF-8")));
			// IvParameterSpec zeroIv = new IvParameterSpec(iv);
			cipher.init(Cipher.ENCRYPT_MODE, secretKey,
					SecureRandom.getInstance("SHA1PRNG"));
			encryptedData = cipher.doFinal(message.getBytes("UTF-8"));
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		String s = Base64_me.encodeStr(encryptedData);
		return s;
	}

	/**
	 * md5����
	 *
	 * @param str
	 *            (Ҫ���ܵ��ַ���)
	 * @return
	 */
	public static String MD5(String str) {
		try {
			MessageDigest md5 = MessageDigest.getInstance("MD5");
			md5.update(str.getBytes("UTF-8"));
			byte[] m = md5.digest();// ����
			return getString(m);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return "";
	}

	private static byte[] FixSize(byte[] input) {
		byte[] output = new byte[8];
		for (int i = 0; i < input.length; i++)
			output[i & 7] ^= input[i];
		return output;
	}

	/**
	 * ���ַ�����������ַ���
	 *
	 * @param b
	 *            ���ַ����飩
	 * @return
	 */
	private static String getString(byte[] b) {
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < b.length; i++) {
			if (Integer.toHexString(0xFF & b[i]).length() == 1)
				sb.append("0").append(Integer.toHexString(0xFF & b[i]));
			else
				sb.append(Integer.toHexString(0xFF & b[i]));
		}
		return sb.toString();
	}
}
